#include "XPlay2.h"
#include <qfiledialog.h>
#include <QDebug>
#include "XDemuxThread.h"
#include <qmessagebox.h>

static XDemuxThread dt;
XPlay2::XPlay2(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
	dt.Start();

}

void XPlay2::OpenFile()
{
	//选择文件
	QString name = QFileDialog::getOpenFileName(this,QString::fromLocal8Bit("选择视频文件"));
	if (name.isEmpty()) return;
	this->setWindowTitle(name);
	int ret = dt.Open(name.toLocal8Bit(),ui.video);
	if (ret == false) {
		QMessageBox::information(0, "error", "Open file failed");
		return;
	}
	startTimer(40);
	setPause(dt.Pause);
	qDebug() << name;
	
}

XPlay2::~XPlay2()
{
	dt.Close();
}

void XPlay2::resizeEvent(QResizeEvent * e)
{
	ui.playPos->move(50, this->height() - 100);
	ui.playPos->resize(this->width() - 100, ui.playPos->height());
	ui.openFile->move(100, this->height() - 150);
	ui.video->resize(this->size());
	ui.isPlay->move(ui.openFile->x() + ui.openFile->width() + 10, ui.openFile->y());
}

void XPlay2::mouseDoubleClickEvent(QMouseEvent * e)
{
	if (isFullScreen()) {
		this->showNormal();
	}
	else {
		this->showFullScreen();
	}
}

void XPlay2::setPause(bool isPause)
{
	if (isPause) {
		ui.isPlay->setText("播放");
	}
	else {
		ui.isPlay->setText("暂停");
	}
	
}

void XPlay2::PlayorPause()
{
	bool status = !dt.Pause;
	setPause(status);
	dt.SetPause(status);
}

void XPlay2::SliderPress()
{
	isSilderPress = true;
}

void XPlay2::SilderRelease()
{
	isSilderPress = false;
	double pos = 0.0;
	pos = (double)ui.playPos->value() / (double)ui.playPos->maximum();
	dt.Seek(pos);
}

void XPlay2::timerEvent(QTimerEvent * e)
{
	if (isSilderPress) return;
	long long total = dt.totalMs;
	if (total > 0) {
		double pos = ((double)dt.pts) / ((double)total);
		int cur_value = ui.playPos->maximum() * pos;
		ui.playPos->setValue(cur_value);
	}
}
